package com.pagoda.nerp.trade.service.impl;

import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.dao.AccModuleDao;
import com.pagoda.nerp.trade.dao.AccUsersDao;
import com.pagoda.nerp.trade.entity.AccModule;
import com.pagoda.nerp.trade.service.ModuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2016/12/6.
 */
@Service
public class ModuleServiceImpl implements ModuleService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AccModuleDao moduleDao;
    @Autowired
    private AccUsersDao usersDao;

    public List<AccModule> queryModuleListByUserIdAndRoleId(Map<String, String> map) {

        //判断用户是否存在
        if (usersDao.queryAccUserInfoByUserId(Integer.parseInt(map.get("userId"))) == null) {
            logger.error(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD.getErrorMsg());
            return null;
        }

        List<AccModule> moduleList = moduleDao.queryByRoleId(Integer.valueOf(map.get("roleId")));


        return moduleDao.queryByRoleId(Integer.valueOf(map.get("roleId")));
    }


    /**
     * 递归算法解析成树形结构
     *
     * @param cid
     * @return
     */
    public AccModule recursiveTree(int cid, List<AccModule> moduleList) {
        //查询cid对应的节点
        AccModule node = null;
        for (AccModule module : moduleList) {
            if (module.getModuleId() == cid) {
                node = module;
                break;
            }
        }

        //查询cid下的所有子节点
        if (node != null) {
            for (AccModule module : moduleList) {
                if (module.getParentModuleId() == cid) {
                    AccModule n = recursiveTree(module.getModuleId(),moduleList);
                    node.getChildModules().add(n);
                }
            }
        }

        return node;
    }

}
